package com.pvdnc.riru.common;

import android.os.IBinder;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class ServiceObserverManager {
    public static final ServiceObserverManager INSTANCE=new ServiceObserverManager();

    private final Map<String, List<ServiceObserver>> mObserverMap=new ConcurrentHashMap<>();

    private List<ServiceObserver> getOrCreate(String serviceName){
        List<ServiceObserver> observerList= mObserverMap.get(serviceName);
        if(observerList==null)
            return new ArrayList<>();
        return observerList;
    }

    public void addObserver(String serviceName,ServiceObserver observer){
        synchronized (mObserverMap) {
            List<ServiceObserver> observerList=getOrCreate(serviceName);
            if(observerList.contains(observer)) {
                return;
            }
            observerList.add(observer);
            mObserverMap.put(serviceName,observerList);
        }
    }

    public void callObserver(String serviceName, IBinder service){
        List<ServiceObserver> observerList=getOrCreate(serviceName);
        for (ServiceObserver observer:observerList){
            observer.onServiceAdd(serviceName, service);
        }
    }
}
